package com.nofeng.wx.third;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class VikaDbApi {

    private final CloseableHttpClient httpClient = HttpClients.createDefault();
    public static Map<String, NoCodeToken> tokenMap = Maps.newHashMap();

    {
        tokenMap.put("300", new NoCodeToken(
                "https://api.vika.cn/fusion/v1",
                "",
                "Bearer uskdPWHFOSXH45yFRKIhgLg"));
    }

    public static Boolean insert(String appKey, String table, String sheetName,Map<String,String> data) {
        try {
            NoCodeToken noCodeToken = tokenMap.get(appKey);
            String url = noCodeToken.getUrl()+"/datasheets/"+table+"/records";
            HttpPatch request = new HttpPatch(url + "?viewId="+sheetName);
            request.setHeader("Content-Type", "application/json; charset=UTF-8");
            request.setHeader("Apikey", noCodeToken.getApiKey());
            request.setHeader("Authorization", noCodeToken.getAuthorization());
            Map<String,Object> req=Maps.newHashMap();
            req.put("fieldKey","name");
            ArrayList< Map<String, Object> > records = Lists.newArrayList();
            req.put("records", records);
            Map<String, Object> recordValue = Maps.newHashMap();

            recordValue.put("fields",data);
            records.add(recordValue);


            StringEntity jsonEntity = new StringEntity(JSONObject.toJSONString(req), StandardCharsets.UTF_8);
            request.setEntity(jsonEntity); // 设置请求体[2,5](@ref)
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 解析成功响应（状态码200系列）
                if (statusCode >= 200 && statusCode < 300) {
                    return true;
                }else{
                    System.out.println(EntityUtils.toString(request.getEntity(), StandardCharsets.UTF_8));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String query(String appKey, String table) {
        //?select=*&order=created_at.desc&limit=10
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            NoCodeToken noCodeToken = tokenMap.get(appKey);
            String url = noCodeToken.getUrl()+"/datasheets/"+table+"/records";
            HttpGet request = new HttpGet(url);
            request.setHeader("Content-Type", "application/json; charset=UTF-8");
            request.setHeader("Authorization", noCodeToken.getAuthorization());

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 解析成功响应（状态码200系列）
                if (statusCode >= 200 && statusCode < 300) {
                    HttpEntity responseEntity = response.getEntity();
                    return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public Boolean delete(String appKey, String table, String where) {
        //?select=*&order=created_at.desc&limit=10
        try {
            NoCodeToken noCodeToken = tokenMap.get(appKey);
            String url = noCodeToken.getUrl();
            HttpDelete request = new HttpDelete(url + table + where);
            request.setHeader("Content-Type", "application/json; charset=UTF-8");
            request.setHeader("Apikey", noCodeToken.getApiKey());
            request.setHeader("Authorization", noCodeToken.getAuthorization());

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 解析成功响应（状态码200系列）
                if (statusCode >= 200 && statusCode < 300) {
                    HttpEntity responseEntity = response.getEntity();
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Boolean update(String appKey, String table, String sheetName,String recordId,Map<String,String> data) {
        try {
            NoCodeToken noCodeToken = tokenMap.get(appKey);
            String url = noCodeToken.getUrl()+"/datasheets/"+table+"/records";
            HttpPatch request = new HttpPatch(url + "?viewId="+sheetName);
            request.setHeader("Content-Type", "application/json; charset=UTF-8");
            request.setHeader("Apikey", noCodeToken.getApiKey());
            request.setHeader("Authorization", noCodeToken.getAuthorization());
            Map<String,Object> req=Maps.newHashMap();
            req.put("fieldKey","name");
            ArrayList< Map<String, Object> > records = Lists.newArrayList();
            req.put("records", records);
            Map<String, Object> recordValue = Maps.newHashMap();
            recordValue.put("recordId",recordId);
            recordValue.put("fields",data);
            records.add(recordValue);


            StringEntity jsonEntity = new StringEntity(JSONObject.toJSONString(req), StandardCharsets.UTF_8);
            request.setEntity(jsonEntity); // 设置请求体[2,5](@ref)
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 解析成功响应（状态码200系列）
                if (statusCode >= 200 && statusCode < 300) {
                    return true;
                }else{
                    System.out.println(EntityUtils.toString(request.getEntity(), StandardCharsets.UTF_8));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static class NoCodeToken {
        private String url;
        private String apiKey;
        private String authorization;

        public NoCodeToken(String url, String apiKey, String authorization) {
            setUrl(url);
            setApiKey(apiKey);
            setAuthorization(authorization);
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getApiKey() {
            return apiKey;
        }

        public void setApiKey(String apiKey) {
            this.apiKey = apiKey;
        }

        public String getAuthorization() {
            return authorization;
        }

        public void setAuthorization(String authorization) {
            this.authorization = authorization;
        }
    }
}